package com.eastfair.security.apiconditioncore;

import org.springframework.util.StringUtils;
import org.springframework.web.servlet.mvc.condition.RequestCondition;

import javax.servlet.http.HttpServletRequest;

/**
 * API版本控制器request规则匹配
 * ligang
 * 2020/03/27
 */
public class ApiVersionRequestCondition implements RequestCondition<ApiVersionRequestCondition> {
    //api版本号
    private int apiVersion;


    public ApiVersionRequestCondition(int versionValue) {
        this.apiVersion = versionValue;
    }

    /**
     * 规则合并
     *
     * @param apiVersionRequestCondition
     * @return
     */
    @Override
    public ApiVersionRequestCondition combine(ApiVersionRequestCondition apiVersionRequestCondition) {
        return new ApiVersionRequestCondition(apiVersionRequestCondition.apiVersion);
    }

    /**
     * 根据request的url进行查找匹配的筛选条件
     */
    @Override
    public ApiVersionRequestCondition getMatchingCondition(HttpServletRequest httpServletRequest) {
        String apiVersionStr = httpServletRequest.getHeader("api-version");
        if (!StringUtils.isEmpty(apiVersionStr)) {
            int apiversion = ConditionUtil.parseVersion(apiVersionStr);
            //获取真实版本号
            apiversion = ConditionData.findRealVersionByMethod(httpServletRequest.getServletPath(), apiversion);
            if (this.apiVersion == apiversion) {
                return this;
            }
        }
        return null;
    }

    /**
     * 排序优先级
     *
     * @param apiVersionRequestCondition
     * @param httpServletRequest
     * @return
     */
    @Override
    public int compareTo(ApiVersionRequestCondition apiVersionRequestCondition, HttpServletRequest httpServletRequest) {
        return apiVersionRequestCondition.apiVersion - this.apiVersion;
    }


}
